package com.hhit.zhgd.task

import com.alibaba.fastjson.JSONObject
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper
import com.hhit.zhgd.component.VideoPlatformProperties
import com.hhit.zhgd.dao.ZhgdDeviceMapper
import com.hhit.zhgd.domain.dto.DeviceStatusRespDTO
import com.hhit.zhgd.utils.RedisUtil
import jakarta.annotation.Resource
import org.quartz.JobExecutionContext
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.scheduling.quartz.QuartzJobBean
import org.springframework.util.DigestUtils
import java.net.URI
import java.net.http.HttpClient
import java.net.http.HttpRequest
import java.net.http.HttpResponse
import java.nio.charset.StandardCharsets

class DeviceStatusTask : QuartzJobBean() {

    private var log = org.slf4j.LoggerFactory.getLogger(DeviceStatusTask::class.java)

    @Resource
    private var videoPlatformProperties: VideoPlatformProperties? = null

    @Autowired
    private var zhgdDeviceMapper: ZhgdDeviceMapper? = null

    @Resource
    private var redisUtil: RedisUtil? = null

    override fun executeInternal(context: JobExecutionContext) {
        log.info("设备状态同步定时任务开始")
        val url =
            "http://" + videoPlatformProperties?.ip + ":" + videoPlatformProperties?.port + videoPlatformProperties?.wvpProperties?.getChannelsUrl + "?page=1&count=2"
        if (!redisUtil!!.hasKey("WVP-accessToken")) {
            val loginUrl =
                "http://" + videoPlatformProperties?.ip + ":" + videoPlatformProperties?.port + videoPlatformProperties?.wvpProperties?.loginUrl
            var hexStr: String? = ""
            hexStr = DigestUtils.md5DigestAsHex(videoPlatformProperties?.passWord?.toByteArray(StandardCharsets.UTF_8)?:"".toByteArray())

            val request = HttpRequest.newBuilder()
                .uri(URI.create(loginUrl+"?username="+videoPlatformProperties?.userName+"&password="+hexStr))
                .header("Content-Type", "application/json")
                .GET()
                .build()
            val response: HttpResponse<String> = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString())
            val loginResJson = JSONObject.parseObject(response.body())

//            val loingRes: String = HttpRequest.get(loginUrl)
//                .contentType("application/json")
//                .form("username", videoPlatformProperties?.userName)
//                .form("password", hexStr)
//                .execute().body()
//            val loginResJson = JSONObject.parseObject(loingRes)
            if (0 == loginResJson.getIntValue("code")) {
                val accessToken = loginResJson.getJSONObject("data").getString("accessToken")
                if (accessToken?.isNotBlank()==true) {
                    redisUtil!!["WVP-accessToken"] = accessToken
                } else {
                    log.error("获取WVP accessToken 失败!")
                    return
                }
            }
        }
        val zhgdDevices = zhgdDeviceMapper!!.selectList(LambdaQueryWrapper())
        for (zhgdDevice in zhgdDevices) {
            val reqUrl = url.replace("{deviceId}", zhgdDevice.deviceNum?:"")
            val deviceStatusRequest = HttpRequest.newBuilder()
                .uri(URI.create(reqUrl))
                .header("Content-Type", "application/json")
                .header("access-token", redisUtil!!["WVP-accessToken"] as String?)
                .GET()
                .build()
            val deviceStatusRes: HttpResponse<String> = HttpClient.newHttpClient().send(deviceStatusRequest, HttpResponse.BodyHandlers.ofString())
//            val deviceStatusRes: String = HttpRequest.get(reqUrl)
//                .contentType("application/json")
//                .header("access-token", redisUtil!!["WVP-accessToken"] as String?)
//                .execute().body()
            val deviceStatusResJson = JSONObject.parseObject(deviceStatusRes.body())
            if (0 == deviceStatusResJson.getIntValue("code")) {
                val deviceStatusRespDTOS: List<DeviceStatusRespDTO> = JSONObject.parseArray(
                    deviceStatusResJson.getJSONObject("data").getJSONArray("list").toJSONString(),
                    DeviceStatusRespDTO::class.java
                )
                for (deviceStatusRespDTO in deviceStatusRespDTOS) {
                    if (zhgdDevice.deviceChannel == deviceStatusRespDTO.channelId) {
                        zhgdDevice.status = (if (deviceStatusRespDTO.status == true) 1 else 0)
                        zhgdDeviceMapper!!.updateById(zhgdDevice)
                    }
                }
            } else {
                log.info("未获取到设备下的通道信息!")
            }
        }
        log.info("设备状态同步定时任务结束")
    }
}